import Vue from 'vue';
import Router from 'vue-router';
import { importCDN } from '@/utils/importCDN';

// in development-env not use lazy-loading, because lazy-loading too many pages will cause webpack hot update too slow. so only in production use lazy-loading;
// detail: https://panjiachen.github.io/vue-element-admin-site/#/lazy-loading

Vue.use(Router);

/* Layout */
import Layout from '@/views/layout/Layout';
import { ROUTER_TYPES, hasRouteAuth } from '@/utils/permission';
// 分页数据
import IndexRouter from './module/IndexRouter'; // 首页
import approvalRouter from './module/approvalRouter'; // 审批
import orderRouter from './module/orderRouter'; // 订单
import resourceRouter from './module/resourceRouter'; // 资源
import operateRouter from './module/operateRouter'; // 资源
import cilentRouter from './module/cilentRouter'; // 客户
import supplierRouter from './module/supplierRouter'; // 供应
import businessRouter from './module/businessRouter'; // 核算
import contractRouter from './module/contractRouter'; // 合同
import settingRouter from './module/settingRouter'; // 设置
import helpRouter from './module/helpRouter'; // 帮助中心
// import chatRouter from './module/chatRouter';

const commonRouter = [
  { path: '/login', name: 'login', component: () => import('@/views/login/index'), hidden: true },
  { path: '/download', name: 'download', component: () => import('@/views/login/download'), hidden: true },
  { path: '/404', name: '404', component: () => import('@/views/404'), hidden: true },
  { path: '/router', component: () => import('@/views/dingdingRouter'), hidden: true },
  { path: '/drawGuess', component: () => import('@/views/help/drawGuess'), hidden: true },
  {
    path: '/', component: Layout, redirect: '/index', name: 'Index', hidden: true,
    children: [
      { path: 'index', component: () => import('@/views/index/index') },
      { path: 'brand/edit/:userId', component: () => import('@/views/user/create/index'), name: 'userUpdate', meta: { title: '编辑用户', headerBarShow: true, activeMenu: '/system/user' }}, // 内品用户编辑页复用，则不展示部门和设置，拼音缩写
      { path: 'user/edit/:userId', component: () => import('@/views/user/create/index'), name: 'editUser', meta: { title: '编辑用户', headerBarShow: true, activeMenu: '/system/user' }}, // 内品用户编辑页复用，则不展示部门和设置，拼音缩写
      { path: 'user/detail/:userId', component: () => import('@/views/user/detail'), name: 'userDetail', meta: { title: '用户详情', headerBarShow: true, activeMenu: '/system/user' }}// 内品用户编辑页复用，则不展示部门和设置，拼音缩写
    ]
  }
];

export const constantRouterMap = [
  ...commonRouter,
  ...IndexRouter,
  ...approvalRouter,
  ...orderRouter,
  ...resourceRouter,
  ...operateRouter,
  ...cilentRouter,
  ...supplierRouter,
  ...businessRouter,
  ...contractRouter,
  ...settingRouter,
  ...helpRouter,
  // ...chatRouter,
  { path: '*', redirect: '/404', hidden: true }
];

const vueRouter = new Router({
  // mode: 'history', //后端支持可开
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRouterMap
});

export default vueRouter;

export function resetRoutes() {
  const filterHeaderFun = item => {
    let isMatch = true;
    if (item.authControl) {
      // isMatch = hasPermission(item.meta.roles);
      isMatch = hasRouteAuth(item.authControl);
    }
    return isMatch;
  };
  const filterFun = item => {
    let isMatch = true;
    if (item.meta && item.meta.authControl) {
      // isMatch = hasPermission(item.meta.roles);
      isMatch = hasRouteAuth(item.meta.authControl);
    }
    if (isMatch && item.children && item.children.length > 1) item.children = item.children.filter(filterFun); // 处理子路由权限
    if (isMatch && item.meta && item.meta.headerParams && item.meta.headerParams.length > 1) item.meta.headerParams = item.meta.headerParams.filter(filterHeaderFun); // 处理子路由权限
    return isMatch;
  };
  const routes = _.cloneDeep(vueRouter.options.routes).filter(filterFun);
  routes.forEach(i => {
    if (i.name === 'userManage') {
      if (hasRouteAuth([ROUTER_TYPES.CRM_USERLIST])) {
        i.redirect = '/user/index';
      } else {
        i.redirect = '/user/role';
      }
    }
  });
  handelJumpRedirect(routes);

  vueRouter.options.routes = routes;
  vueRouter.matcher = new Router({
    // mode: 'history', //后端支持可开
    scrollBehavior: () => ({ y: 0 }),
    routes
  }).matcher; // 重置matcher才能生效最新routes规则
}

/**
 * 处理当没有该页面权限时的首页位置
 *
 * @param  {array}    routes      路由列表
 * @param  {string}   routeName   路由名字
 * @param  {string}   routePath   默认路由首页
 */
function handelJumpRedirect(routesParams) {
  let tempPath = '';
  function loop(routes) {
    for (let i = 0; i < routes.length; i++) {
      const routeItem = routes[i];
      if (!routeItem.hidden) {
        // 查找侧边栏第一个路由当作首页
        const a = routeItem.path.indexOf('/') >= 0 ? '' : '/';
        tempPath = tempPath + a + routeItem.path;
        if (routeItem.children && routeItem.children.length) {
          loop(routeItem.children);
        } else {
          findAndSetIndexRedirect(routesParams, tempPath === '' ? routeItem.path : tempPath);
        }
        return;
      }
    }
  }
  loop(routesParams);
}

function findAndSetIndexRedirect(routes, path) {
  routes.forEach(i => {
    if (i.name === 'Index') i.redirect = path;
  });
}

vueRouter.beforeEach(async(to, from, next) => {
  if (to.meta && Array.isArray(to.meta.CDN) && to.meta.CDN.length) {
    importCDN(to.meta.CDN);
  }
  next();
});
